﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;

namespace VPLink2013.Framework.Extensions
{
    public static partial class FrameworkExtensions
    {
        public static bool IsNull(this object input)
        {
            if (input == null)
            {
                return true;
            }
            return false;
        }

        public static bool IsNotNull(this object input)
        {
            return input.IsNull() == false;
        }

        public static string ToEmptyIfNull(this object input)
        {
            try
            {
                if (input == null)
                {
                    return string.Empty;
                }

                return input.ToString(); ;

            }
            catch (Exception)
            {
                //TODO :log
                return string.Empty ;
            }
        }

        public static string ToJson<T>(this T input) where T:class
        {
            try
            {
                if (input == null)
                {
                    return "{}";
                }
                
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                using (MemoryStream stream = new MemoryStream())
                {
                    serializer.WriteObject(stream, input);
                    return Encoding.UTF8.GetString(stream.ToArray());
                }

            }
            catch (Exception ex)
            {
                //TODO : log
                string msg = ex.Message;
                return "{}";
            }
        }

        public static string ToXML<T>(this T input) where T : class
        {
            try
            {
                if (input == null)
                {
                    return "";
                }

                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                using (MemoryStream stream = new MemoryStream())
                {
                    serializer.WriteObject(stream, input);
                    return Encoding.UTF8.GetString(stream.ToArray());
                }

            }
            catch (Exception ex)
            {
                //TODO : log
                string msg = ex.Message;
                return "";
            }
        }
    }
}
